package patrol.mobile.com.mobilepatrol.activity.security.emergency;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.security.ConsTitles;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.DictListBean;
import patrol.mobile.com.mobilepatrol.bean.ProtectCheckBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.widget.MySpinner;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

public class ZHCXEmergencyProtectCheckActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.spInspectionMode)
    MySpinner spInspectionMode;
    @BindView(R.id.spSituation)
    MySpinner spSituation;

    private List<String> inspectionModeList = new ArrayList<>();
    private List<String> situationList = new ArrayList<>();

    private String inspectionMode = "";
    private String situation = "";

    @BindView(R.id.tv_inspectionDate)
    TextView tvInspectionDate;
    @BindView(R.id.tv_orgName)
    TextView tvOrgName;
    @BindView(R.id.tv_inspectionName)
    TextView tvInspectionName;
    @BindView(R.id.tv_leadName)
    TextView tvLeadName;
    @BindView(R.id.tv_duty)
    TextView tvDuty;
    @BindView(R.id.tv_dutyPersonnel)
    TextView tvDutyPersonnel;
    @BindView(R.id.tv_exactDate)
    TextView tvExactDate;
    @BindView(R.id.tv_problems)
    EditText tvProblems;@BindView(R.id.tv_deal_sug)
    EditText tv_deal_sug;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.rb_shidi)
    RadioButton rbShiDi;
    @BindView(R.id.rb_phone)
    RadioButton rbPhone;
    @BindView(R.id.rb_control)
    RadioButton rbControl;
    @BindView(R.id.rb_zai)
    RadioButton rbZai;
    @BindView(R.id.rb_buzai)
    RadioButton rbBuZai;


    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_zhcx_protect_check1;
    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(ZHCXEmergencyProtectCheckActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText(ConsTitles.EMERGENCY_PROTECT_CHECK_1);
    }

    @Override
    public void initData() {
        super.initData();
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void setListener() {
        String id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            requestData(id);
        }
        getDictList("inspectionMode");
        getDictList("situation");

    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @OnClick({R.id.tv_save})
    public void onTClick(View v) {

        switch (v.getId()) {
            case R.id.tv_save:
                submit();
                break;
        }

    }

    @OnCheckedChanged({R.id.rb_shidi, R.id.rb_phone, R.id.rb_control, R.id.rb_zai, R.id.rb_buzai})
    public void OnCheckedChangeListener(CompoundButton view, boolean ischanged) {
        switch (view.getId()) {
            case R.id.rb_shidi:
                if (ischanged) {//注意：这里一定要有这个判断，只有对应该id的按钮被点击了，ischanged状态发生改变，才会执行下面的内容
                    //这里写你的按钮变化状态的UI及相关逻辑
                }
                break;
            case R.id.rb_phone:
                if (ischanged) {
                    //这里写你的按钮变化状态的UI及相关逻辑
                }
                break;
            case R.id.rb_control:
                if (ischanged) {
                    //这里写你的按钮变化状态的UI及相关逻辑
                }
                break;
            case R.id.rb_zai:
                if (ischanged) {
                    //这里写你的按钮变化状态的UI及相关逻辑
                }
                break;
            case R.id.rb_buzai:
                if (ischanged) {
                    //这里写你的按钮变化状态的UI及相关逻辑
                }
                break;
            default:
                break;
        }
    }


    private void requestData(String id) {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.EMERGENCY_PROTECT_CHECK_ENTITY);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {
                ProtectCheckBean protectCheckBean = GsonUtil.GsonToBean(response, ProtectCheckBean.class);
                tvInspectionDate.setText(protectCheckBean.getInspectionDate());
                tvOrgName.setText(protectCheckBean.getOrgName());
                tvLeadName.setText(protectCheckBean.getLeadName());
                tvInspectionName.setText(protectCheckBean.getCheckPerson());
                tvDuty.setText(protectCheckBean.getDuty());
                tvDutyPersonnel.setText(protectCheckBean.getDutyPersonnel());
                tvExactDate.setText(protectCheckBean.getExactDate());
                tvProblems.setText(protectCheckBean.getProblems());
                tv_deal_sug.setText(protectCheckBean.getAuditFlag());// TODO: 2019/2/17 处理意见

                String type = protectCheckBean.getInspectionMode();
                if (type.equals("1")) {
                    rbShiDi.setChecked(true);
                } else if (type.equals("2")) {
                    rbPhone.setChecked(true);
                } else if (type.equals("3")) {
                    rbControl.setChecked(true);
                }


                String zai = protectCheckBean.getSituation();
                if (zai.equals("1")) {
                    rbZai.setChecked(true);
                } else if (zai.equals("2")) {
                    rbBuZai.setChecked(true);
                }



                List<DeviceDetailImgBean> deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(ZHCXEmergencyProtectCheckActivity.this);

                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
//                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });

            }
        });
    }

    ArrayList<ImageItem> images = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
            }
        }
    }


    @Override
    public void onItemClick(View view, int position) {
//        switch (position) {
//            case IMAGE_ITEM_ADD:
//                List<String> names = new ArrayList<>();
//                names.add("拍照");
//                names.add("相册");
//                showDialog(new SelectDialog.SelectDialogListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        switch (position) {
//                            case 0: // 直接调起相机
//                                /**
//                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
//                                 *
//                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
//                                 *
//                                 * 如果实在有所需要，请直接下载源码引用。
//                                 */
//                                //打开选择,本次允许选择的数量
//                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
//                                Intent intent = new Intent(ZHCXEmergencyProtectCheckActivity.this, ImageGridActivity.class);
//                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
//                                startActivityForResult(intent, REQUEST_CODE_SELECT);
//                                break;
//                            case 1:
//                                //打开选择,本次允许选择的数量
//                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
//                                Intent intent1 = new Intent(ZHCXEmergencyProtectCheckActivity.this, ImageGridActivity.class);
//                                /* 如果需要进入选择的时候显示已经选中的图片，
//                                 * 详情请查看ImagePickerActivity
//                                 * */
////                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
//                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
//                                break;
//                            default:
//                                break;
//                        }
//
//                    }
//                }, names);
//                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
//        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }


    private void submit() {
        final HttpSender sender = new HttpSender(this, baseUrl, Urls.EMERGENCY_DURITY_UPLOAD);

        HashMap<String, String> idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        HashMap<String, Object> map1 = new HashMap<>();

        map1.put("inspectionDate", tvInspectionDate.getText().toString());
        map1.put("orgName", tvOrgName.getText().toString());
        map1.put("inspectionName", tvInspectionName.getText().toString());
        map1.put("leadName", tvLeadName.getText().toString());
        map1.put("duty", tvDuty.getText().toString());
        map1.put("dutyPersonnel", tvDutyPersonnel.getText().toString());
        map1.put("exactDate", tvExactDate.getText().toString());
        map1.put("inspectionMode", spInspectionMode.getmText().getText().toString());
        map1.put("situation", spSituation.getmText().getText().toString());
        map1.put("problems", tvProblems.getText().toString());
        map1.putAll(idDateBmnameMap);
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("abkDuty", GsonUtil.map2Json(map1));

        List<ImageItem> images = adapter.getImages();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (int i = 0; i < images.size() - oldImgInfo.size(); i++) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("abkDuty");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        oldImgInfo.addAll(upImgInfoBeanList);
        map2.put("sysAttachmentsJson", GsonUtil.bean2Json(oldImgInfo));

        sender.postJson(GsonUtil.map2Json(map2), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                sender.dismissDialog();
                Toast.makeText(ZHCXEmergencyProtectCheckActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    int state = jsonObject.getInt("state");
                    if (200 == state) {
                        sender.dismissDialog();
                        upImg();
                    } else {
                        Toast.makeText(ZHCXEmergencyProtectCheckActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            List<ImageItem> images = adapter.getImages();
            for (ImageItem image : images) {
                File file = new File(image.path);
                list.add(file);
            }

            List<Map<String, String>> params = new ArrayList<>();
            for (UpImgInfoBean upImgInfoBean : oldImgInfo) {
                Map<String, String> map = new HashMap<>();
                map.put("id", upImgInfoBean.getId());
                map.put("type", "abkDuty");
                params.add(map);
            }

            LuBanHelper luBanHelper = new LuBanHelper(ZHCXEmergencyProtectCheckActivity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("state") == 200) {
                            finish();
                            Toast.makeText(ZHCXEmergencyProtectCheckActivity.this, "上传成功！", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    private void getDictList(final String dictType) {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.DICT_LIST);
        HashMap<String, String> map = new HashMap<>();
        map.put("dictType", dictType);
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser jp = new JsonParser();
                JsonObject jo = jp.parse(response).getAsJsonObject();
                JsonArray listArray = jo.getAsJsonArray("list");
                List<DictListBean> dictListBeanList = GsonUtil.jsonToList(listArray.toString(), DictListBean.class);
                if (dictType.equals("inspectionMode")) {
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        inspectionModeList.add(dictListBeanList.get(i).getLabel());
                    }
                    spInspectionMode.setmDatas(inspectionModeList, new MySpinner.CallBack() {
                        @Override
                        public void onSelect(int postion) {
                            inspectionMode = inspectionModeList.get(postion);
                        }
                    });
                } else if (dictType.equals("situation")) {
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        situationList.add(dictListBeanList.get(i).getLabel());
                    }
                    spSituation.setmDatas(situationList, new MySpinner.CallBack() {
                        @Override
                        public void onSelect(int postion) {
                            situation = situationList.get(postion);
                        }
                    });
                }


            }
        });
    }

}
